package cn.net.isir.service2;

import com.alipay.api.response.AlipayTradeCreateResponse;
import cn.net.isir.common.ResultObject;
import cn.net.isir.common.config.AlipayConfig;
import cn.net.isir.common.pay.alipay.AlipayAgentAPI;
import cn.net.isir.core.BasicService2;
import cn.net.isir.core.SetBasicDao;
import cn.net.isir.dao.*;
import cn.net.isir.entity.*;
import cn.net.isir.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AlipayMinipPayUnifiedOrderInfoService extends BasicService2<AlipayMinipPayUnifiedOrderInfo> {
    @SetBasicDao
    @Resource
    private AlipayMinipPayUnifiedOrderInfoDao alipayMinipPayUnifiedOrderInfoDao;
    @Resource
    private AlipayAuthDao alipayAuthDao;
    @Resource
    private OrderDao orderDao;
    @Resource
    private ShopDao shopDao;
    @Resource
    private AlipayMinipPayUnifiedOrderResponseInfoDao alipayMinipPayUnifiedOrderResponseInfoDao;
    @Resource
    private PaymentDao paymentDao;

    /**
     * 支付宝统一下单接口
     *
     * @param userid  用户id
     * @param shopid  店铺id
     * @param orderid 订单id
     * @return 结果
     */
    public ResultObject uniformOrder(String userid, String shopid, String orderid) {
        ResultObject ro = new ResultObject();
        // 判断商户是否已经授权
        Shop shop = shopDao.selectByPrimaryKey(shopid);
        if (StringUtils.isBlank(shop.getAlipayMerchantId())) {
            ro.setResult(501);
            ro.setMessage("商户尚未绑定支付信息，无法在线支付。");
            return ro;
        }
        Payment payment = paymentDao.selectByPrimaryKey(shop.getAlipayMerchantId());
        if (!"3".equals(payment.getSignStatus())) {
            ro.setResult(501);
            ro.setMessage("商户尚未绑定签约信息，无法在线支付。");
            return ro;
        }
//        AlipayAuth alipayAuth = new AlipayAuth();
//        alipayAuth.setShopId(shopid);
//        alipayAuth = alipayAuthDao.selectOne(alipayAuth);
//        if (alipayAuth == null) {
//            ro.setResult(501);
//            ro.setMessage("商户尚未绑定支付信息，无法在线支付。");
//            return ro;
//        }
//        // 查询店铺信息
//        Shop shop = shopDao.selectByPrimaryKey(shopid);
//        if ("0".equals(shop.getAlipayAuthStatus())) {
//            ro.setResult(501);
//            ro.setMessage("商户尚未绑定授权信息，无法在线支付。");
//            return ro;
//        }
//        if (!"3".equals(shop.getAlipaySignStatus())) {
//            ro.setResult(501);
//            ro.setMessage("商户尚未绑定签约信息，无法在线支付。");
//            return ro;
//        }
//        if (shop.getAlipayBusinessInfo() == null) {
//            ro.setResult(501);
//            ro.setMessage("商户尚未绑定支付信息，无法在线支付。");
//            return ro;
//        }

        // 查询订单信息
        Order order = orderDao.selectByPrimaryKey(orderid);
        if (order == null) {
            ro.setResult(500);
            ro.setMessage("订单不存在");
            return ro;
        }
        if (order.getIsPaid() == 1) {
            ro.setResult(500);
            ro.setMessage("该订单已支付");
            return ro;
        }
        if (!shopid.equals(order.getShopId())) {
            ro.setResult(500);
            ro.setMessage("店铺和订单信息不匹配");
            return ro;
        }
//        if (!"1".equals(shop.getAlipayAuthStatus())) {
//            ro.setResult(501);
//            ro.setMessage("商户尚未绑定支付信息，无法在线支付。");
//            return ro;
//        }
//        if (!"3".equals(shop.getAlipaySignStatus())) {
//            ro.setResult(501);
//            ro.setMessage("商户尚未绑定支付信息，无法在线支付。");
//            return ro;
//        }

        AlipayAuth alipayAuth = alipayAuthDao.selectByPrimaryKey(payment.getBindingAuthInfoId());

        // 记录统一下单日志
        AlipayMinipPayUnifiedOrderInfo requestInfo = new AlipayMinipPayUnifiedOrderInfo();
        requestInfo.setAppid(AlipayConfig.getApp_id());
        requestInfo.setMerchantId(alipayAuth.getUser_id());
        requestInfo.setApp_auth_token(alipayAuth.getApp_auth_token());
        requestInfo.setOut_trade_no(order.getNo());
        requestInfo.setTotal_amount(order.getFinalTotal());
        requestInfo.setSubject(shop.getName() + "-点餐");
        requestInfo.setSys_service_provider_id(AlipayConfig.getProvider_id());
        requestInfo.setUserId(userid);
        requestInfo.setStatus("paying");//收到异步通知后，改为paid
        requestInfo.setCreateUser(userid);
        alipayMinipPayUnifiedOrderInfoDao.insert(requestInfo);
        // 更新订单信息为支付中
        order.setOrderStatus("paying");
        orderDao.update(order);

        //请求接口
        AlipayTradeCreateResponse response =
                AlipayAgentAPI.alipayTradeCreate(
                        alipayAuth.getApp_auth_token(),
                        order.getNo(),
                        null,
                        userid,
                        order.getFinalTotal().toString(),
                        shop.getName() + "-点餐",
                        AlipayConfig.getProvider_id());

        if (response == null) {
            ro.setResult(500);
            ro.setMessage("未知错误。");
            return ro;
        }

        // 保存返回结果日志
        AlipayMinipPayUnifiedOrderResponseInfo responseInfo = new AlipayMinipPayUnifiedOrderResponseInfo();
        responseInfo.setOrderInfoId(requestInfo.getId());
        responseInfo.setCode(response.getCode());
        responseInfo.setMsg(response.getMsg());
        responseInfo.setOut_trade_no(response.getOutTradeNo());
        responseInfo.setTrade_no(response.getTradeNo());
        responseInfo.setSign(null);
        responseInfo.setStatus(null);
        responseInfo.setCreateUser(userid);
        alipayMinipPayUnifiedOrderResponseInfoDao.insert(responseInfo);
        if ("10000".equals(response.getCode()) && "Success".equals(response.getMsg())) {
            ro.setResult(200);
            ro.setMessage("success");
            ro.setObject(response.getTradeNo());
            return ro;
        }
        ro.setResult(500);
        ro.setMessage(responseInfo.getMsg());
        return ro;
    }
}
